#!/usr/bin/py2
# -*- coding: utf-8 -*-
#encoding=utf-8

# @author Funsion Wu
# scrapyd 任务管理，含执行，列表，取消，状态查询等功能

from scrapyd_api import ScrapydAPI
from optparse import OptionParser
from pprint import pprint
import sys

parser = OptionParser()
parser.add_option( '-r', '--run', dest='run', action='store_true', default=False, help=u'执行 funsion spider' )
parser.add_option( '-c', '--cancel', dest='cancel', action='store_true', default=False, help=u'取消Job，请输入Job Id' )
parser.add_option( '-j', '--job_id', dest='job_id', action = "store", type = 'string', help=u'请输入Job Id' )
parser.add_option( '-l', '--list', dest='list', action='store_true', default=False, help=u'列出所有的 Jobs' )
(options, args) = parser.parse_args()

scrapyd = ScrapydAPI('http://localhost:6800')

if len(sys.argv) <= 1:
    parser.print_help()

if options.run:
    print "\n----------------- Run Success ------------------"
    job_id = scrapyd.schedule('funsion', 'funsion')
    print '%s Status: %s' %(job_id, scrapyd.job_status('funsion', job_id))

if options.list:
    print "\n--------------- Project List ------------------"
    pprint(scrapyd.list_projects())
    print "\n--------------- Spider List ------------------"
    pprint(scrapyd.list_spiders('funsion'))
    print "\n--------------- Job List ------------------"
    pprint(scrapyd.list_jobs('funsion'))

if options.job_id:
    status = scrapyd.job_status('funsion', options.job_id)
    status = status if status else 'Not Exist'
    print "\n----------------- Job Status ------------------"
    print '%s Status: %s' % (options.job_id, status)

if options.cancel:
    if not options.job_id:
        print "\n必须输入Job Id，请和 -j 参数组合使用\n"
        sys.exit()

    print "\n----------------- Cancel Success ------------------"
    scrapyd.cancel('funsion', options.job_id)
    print '%s Status: %s' % (options.job_id, status)

print
